<template>
<!-- <up-button icon="plus" text="添加新订单" @click="goTo('/pagesub/order/add')"></up-button> -->
<view class="fixedArea">
	<view class="fixedBtn flex-rcc search" @tap="goTo('/pagesub/history/list')">查账</view>
	<template v-if="order.list.length>0">
		<view class="fixedBtn flex-rcc billing" @tap="billHandle">结算</view>
		<view class="fixedBtn flex-rcc add" @tap="searchHzsOrder">
			<u-icon name="search" color="#fff" size="56rpx"></u-icon>
		</view>
	</template>
	<view class="fixedBtn flex-rcc add" @tap="goTo('/pagesub/order/add')">
		<u-icon name="plus" color="#fff" size="56rpx"></u-icon>
	</view>
</view>

<u-collapse :value="defaultCollapse">
    <u-collapse-item
		v-for="item in list"
		:title="`[${orderTypeFilter(item.type)}] `+item.hanfuName"
		:value="dynastyFilter(item.dynasty)"
		:label="dayjs(item.timestamp).format('YYYY年MM月DD日 HH:mm:ss')"
		:name="item.timestamp"
		:class="{'redBg': item.type===1&&item.leaseStatus===1, 'greenBg': item.type===1&&item.leaseStatus===0}"
    >
		<!-- :label="$u.timeFormat(item.timestamp, 'yyyy年mm月dd日 hh:MM:ss')" -->
		<!-- <u-tag text="归还" type="success"></u-tag>
		<u-tag text="租赁中" type="warning"></u-tag> -->
		<OrderItem :item="item"></OrderItem>
		<view class="btnGroup">
			<up-button
				v-show="item.type===1&&item.leaseStatus===1"
				plain 
				class="btn" 
				type="success" 
				icon="edit-pen" 
				text="归还" 
				@click="order.changeStatus(item.timestamp, 0)"
			></up-button>
			<up-button
				plain 
				class="btn" 
				type="warning" 
				icon="edit-pen" 
				text="编辑" 
				@click="editOrder(item)"
			></up-button>
			<up-button 
				class="btn" 
				type="error" 
				icon="trash" 
				text="删除" 
				@click="deleteOrder(item.timestamp)"
			></up-button>
		</view>
    </u-collapse-item>
</u-collapse>
<u-empty 
	v-if="order.list.length===0" 
	text="今日还没有订单请点 + 添加"
	mode="order" 
	icon="http://cdn.uviewui.com/uview/empty/order.png"
	marginTop="200rpx"
></u-empty>
<!-- 结算弹窗 -->
<u-modal 
	:show="popup.show" 
	:title="popup.title" 
	:content='popup.content' 
	:showConfirmButton="false" 
	:closeOnClickOverlay="true"
	@close="popup.show = false"
	width="710rpx"
>
	<view class="slot-content" v-if="popup.show">
		<u-alert
			:title="popup.content"  
			type="warning" 
			center
		></u-alert>
		<u-cell 
			v-for="(item, i) in popup.hzsExpend"
			:value="item.makeupFees" 
			rightIcon="" 
			:key="i" 
			@click="searchOrderByName(item.name)"
		>
			<template #title>
				<view @click="">{{`${item.name} (${item.count}个)${item.typeName}`}}</view>
			</template>
			<template #value>
				<view>{{item.makeupFees}}</view>
				<up-button type="primary" text="复制" size="mini" class="copy" @click="copyMsg(item)"></up-button>
			</template>
		</u-cell>
	</view>
</u-modal>
</template>

<script setup>
import { onShow, onUnload } from '@dcloudio/uni-app'
import { goTo, shareScreen } from '@/utils/helper'
import { useOrderStore, useGoodsStore } from '@/stores'
import { dynastyFilter, orderType, orderTypeFilter, numFilter } from '@/utils/data'
import { changeData } from '@/utils/file'
import dayjs from 'dayjs'
import OrderItem from '@/components/OrderItem'

const order = useOrderStore()
const popup = reactive({
	show: false,
	title: '',
	content: '',
	hzsExpend: []
})
const list = ref([]) 
const defaultCollapse = ref([])
let searchReg = null

onShow(()=>{
	const nowDate = dayjs()
	const d = nowDate.date()
	const h = nowDate.hour()
	// 早上7点自动清除昨日订单数据
	if(order.clearDay!==d && (h>=7)){
		order.setClearDay(d)
		order.clearYesterdayOrder()
	}
	list.value = searchReg ? order.list.filter(item=>item.makeupArtist.match(searchReg)) :  order.list
	defaultCollapse.value = []
})

function editOrder(item){
	// order.setEditTmp(item)
	goTo('/pagesub/order/add?order='+JSON.stringify(item))
}

function deleteOrder(timestamp){
	uni.showModal({
		title: '温馨提示',
		content: `请确认是否要删除当前选中的订单？`,
		success(res){
			if (res.confirm) {
				order.deleteOrder(timestamp)
				list.value = order.list
			}
		}
	})
}
function searchOrderByName(content){
	searchReg = new RegExp(content)
	list.value = order.list.filter(item=>item.makeupArtist.match(searchReg)) 
	uni.setNavigationBarTitle({title: content+"的订单"})
}
function searchHzsOrder(){
	uni.showModal({
		title: '搜化妆师的订单',
		placeholderText: "请输入要搜索的化妆师名字",
		editable: true,
		success(res){
			if (res.confirm) {
				if(res.content){
					searchOrderByName(res.content)
				}else{
					searchReg = null
					list.value = order.list
					uni.setNavigationBarTitle({title: "今日"})
				}
			}
		}
	})
}
function billHandle(){
	const nowDate = dayjs();
	// 每天早上7点前都算前一天
	const currentDate = (nowDate.hour() < 7) ? nowDate.subtract(1, 'day') : nowDate;
	const title = `${uni.$u.timeFormat(currentDate, 'yyyy-mm-dd')}结算结果`;
	let totalCollect = 0, totaFees = 0;
	const groups = [];
	for(let item of order.list){
		totalCollect += Number(item.price)
		totaFees += Number(item.makeupFees)
		const index = groups.findIndex(it=>it.name===item.makeupArtist)
		if(index>-1){
			groups[index].makeupFees += Number(item.makeupFees)
			groups[index].desc += `+${item.makeupFees}`
			groups[index].count++
		}else if(item.makeupArtist){
			groups.push({
				typeName: item.type===3?'跟拍':'妆',
				name: item.makeupArtist,
				makeupFees: Number(item.makeupFees), 
				count: 1,
				desc: item.makeupFees
			})
		}
	}
	const totalProfit = numFilter(totalCollect - totaFees)
	const totalMoney = numFilter(totalCollect)
	popup.title = title
	popup.content = `总收款${totalMoney}元，总支出${totaFees}元，总利润${totalProfit}元`
	popup.show = true
	popup.hzsExpend = groups
	// 保存数据到APP本地私有目录内 安卓10+
	var _pathUrl = "_history/" + currentDate.format('YYYY-MM/DD') + '.json'
	// plus.io.convertLocalFileSystemURL(）
	// /storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/_history/2024-02/29.json
	changeData(_pathUrl, 0, {totalCollect: totalMoney, totaFees, totalProfit, list: order.list})
	// 开启自动截屏
	// setTimeout(shareScreen, 1000)
}
function copyMsg({makeupFees, count, desc, typeName}){
	const word = (makeupFees == desc) ? '' : `${desc}=`
	uni.setClipboardData({
		data: `${count}个${typeName}，${word}${makeupFees}元`,
		success: function () {
			uni.showToast({title: '复制成功'})
		}
	});
}
</script>

<style lang="scss" scoped>
.fixedArea{
	position: fixed;
	bottom: 50rpx;
	left: 20rpx;
	z-index: 2;
	.fixedBtn{
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		box-shadow: 0 0 10rpx #ccc;
		color: #fff;
		margin-top: 20rpx;
	}
	.add{
		background-color: #2979ff;
	}
	.billing{
		background-color: #f56c6c;
	}
	.search{
		background-color: #666666;
	}
}
.redBg{
	background-color: #ffe6e6;
}
.greenBg{
	background-color: #d8f3d8;
}
.btnGroup{
	width: 100%;
	display: flex;
	justify-content: flex-end;
	align-items: center;
	padding-top: 20rpx;
	.btn{
		width: 200rpx!important;
	}
}
.slot-content{
	.copy{
		width: 80rpx;
		margin-left: 10rpx;
	}
}
</style>
